package net.zoneland.zrdp.framework.web.service;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import net.zoneland.zrdp.common.constant.CacheConstants;
import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.core.redis.RedisService;
import net.zoneland.zrdp.common.exception.user.UserPasswordNotMatchException;
import net.zoneland.zrdp.common.exception.user.UserPasswordRetryLimitExceedException;
import net.zoneland.zrdp.common.utils.MessageUtils;
import net.zoneland.zrdp.common.utils.SecurityUtils;
import net.zoneland.zrdp.framework.manager.AsyncManager;
import net.zoneland.zrdp.framework.manager.factory.AsyncFactory;
import net.zoneland.zrdp.framework.security.context.AuthenticationContextHolder;

import javax.annotation.Resource;

/**
 * 登录密码方法
 *
 * @author zonevue
 */
@Component
public class SysPasswordService
{
    @Resource
    private RedisService redisService;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(final String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(final SysUser user)
    {
        final Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        final String username = usernamePasswordAuthenticationToken.getName();
        final String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        final String retryCountStr = redisService.getCacheString(getCacheKey(username));
        int retryCount = retryCountStr == null ? 0 : Integer.parseInt(retryCountStr);

        if (retryCount >= maxRetryCount) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisService.setCacheString(getCacheKey(username), Integer.toString(retryCount), lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(final SysUser user, final String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(final String loginName) {
        if (Boolean.TRUE.equals(redisService.hasKey(getCacheKey(loginName)))) {
            redisService.deleteObject(getCacheKey(loginName));
        }
    }
}
